import React, {useState} from 'react';
import {ScrollView, View} from 'react-native';
import {useTranslation} from 'react-i18next';
import {useForm, Controller} from 'react-hook-form';
import {userApi} from '@/services/api';
import Toast from '@/utils/toast';
import {useSafeAreaInsets} from 'react-native-safe-area-context';
import {ErrorText} from '@/components/ErrorText';
import {Icon, useAppTheme, Button, Text, TextInput} from 'tsun-smart-ui';
type FormData = {
  currentPassword: string;
  newPassword: string;
  confirmPassword: string;
};

const ChangePasswordScreen = () => {
  const {t} = useTranslation();
  const theme = useAppTheme();

  const [showCurrentPassword, setShowCurrentPassword] = useState(false);
  const [showNewPassword, setShowNewPassword] = useState(false);
  const [showConfirmPassword, setShowConfirmPassword] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const {bottom} = useSafeAreaInsets();

  const {
    control,
    handleSubmit,
    formState: {errors},
    watch,
  } = useForm<FormData>({
    defaultValues: {
      currentPassword: '',
      newPassword: '',
      confirmPassword: '',
    },
  });

  const newPassword = watch('newPassword');
  // const dispatch = useDispatch();
  // 提交处理
  const submitForm = async (data: FormData) => {
    if (data.newPassword === data.currentPassword) {
      Toast.error({
        message: t('common.password.newpassword.tip', {
          defaultValue: '新密码不能与当前密码相同',
        }),
      });
      return;
    }
    setIsLoading(true);
    try {
      await userApi.changePassword({
        password: data.currentPassword,
        newpassword1: data.confirmPassword,
      });
      Toast.success({
        message: t('common.editSuccessText', {defaultValue: '修改成功'}),
      });
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <ScrollView
      className="flex-1 "
      contentContainerClassName=" justify-between flex-1"
      style={{
        paddingBottom: 27 + bottom,
      }}>
      <View className="flex-1">
        <View className="p-4">
          {/* 当前密码 */}
          <View className="mb-2">
            <Controller
              control={control}
              name="currentPassword"
              rules={{
                required: t('login.password.current', {
                  defaultValue: '此字段为必填项',
                }),
              }}
              render={({field: {onChange, value}}) => (
                <TextInput
                  left="password"
                  placeholder={t('login.form.password.placeholder', {
                    defaultValue: '请输入密码',
                  })}
                  value={value}
                  label={t('common.password.currentPassword', {
                    defaultValue: '当前密码',
                  })}
                  onChangeText={onChange}
                  secureTextEntry={!showCurrentPassword}
                  right={
                    <Icon
                      size={16}
                      name={showCurrentPassword ? 'eye' : 'eye-off'}
                      onPress={() =>
                        setShowCurrentPassword(!showCurrentPassword)
                      }
                    />
                  }
                />
              )}
            />
            <View className="pt-2 ml-14">
              {errors.currentPassword && (
                <ErrorText text={errors.currentPassword.message!} />
              )}
            </View>
          </View>

          {/* 新密码 */}
          <View className="mb-2">
            <Controller
              control={control}
              name="newPassword"
              rules={{
                required: t('common.password.newpassword.tip', {
                  defaultValue: '此字段为必填项',
                }),
                minLength: {
                  value: 6,
                  message: t('common.password.newpassword.rule', {
                    defaultValue: '密码长度至少为6位',
                  }),
                },
              }}
              render={({field: {onChange, value}}) => (
                <TextInput
                  left="password"
                  placeholder={t('login.form.password.placeholder', {
                    defaultValue: '请输入密码',
                  })}
                  label={t('common.password.newpassword', {
                    defaultValue: '新密码',
                  })}
                  value={value}
                  onChangeText={onChange}
                  secureTextEntry={!showNewPassword}
                  right={
                    <Icon
                      size={16}
                      name={showNewPassword ? 'eye' : 'eye-off'}
                      onPress={() => setShowNewPassword(!showNewPassword)}
                    />
                  }
                />
              )}
            />
            <View className="pt-2 ml-14">
              {errors.newPassword && (
                <ErrorText text={errors.newPassword.message!} />
              )}
            </View>
          </View>

          {/* 确认密码 */}
          <View className="mb-4">
            <Controller
              control={control}
              name="confirmPassword"
              rules={{
                required: t('common.password.newpassword.tip3', {
                  defaultValue: '此字段为必填项',
                }),
                validate: value =>
                  value === newPassword ||
                  t('personal.passwordRule', {
                    defaultValue: '两次输入的密码不一致',
                  }),
              }}
              render={({field: {onChange, value}}) => (
                <TextInput
                  left="repassword"
                  placeholder={t('login.form.password.placeholder', {
                    defaultValue: '请输入密码',
                  })}
                  value={value}
                  onChangeText={onChange}
                  secureTextEntry={!showConfirmPassword}
                  right={
                    <Icon
                      size={16}
                      name={showConfirmPassword ? 'eye' : 'eye-off'}
                      onPress={() =>
                        setShowConfirmPassword(!showConfirmPassword)
                      }
                    />
                  }
                />
              )}
            />
            <View className="pt-2 ml-14">
              {errors.confirmPassword && (
                <ErrorText text={errors.confirmPassword.message!} />
              )}
            </View>
          </View>
          <Text
            className="mb-6 px-1"
            variant="caption"
            style={{color: theme.colors?.neutral?.primary}}>
            {t('userSetting.security.strongPassword.create.tip', {
              defaultValue:
                '为了保证账户安全，请创建一个强密码，避免使用生日、手机号等容易被猜测的密码。',
            })}
          </Text>
        </View>
      </View>
      <View className="mx-4">
        <Button
          onPress={handleSubmit(submitForm)}
          disabled={isLoading}
          title={t('common.confirmButtonText', {defaultValue: '确认修改'})}
          loading={isLoading}
        />
      </View>
    </ScrollView>
  );
};

export default ChangePasswordScreen;
